<template>
  <div class="register" v-title data-title="书湘-忘记密码">
    <el-card class="box-card">
      <div slot="header" class="clearfix">忘记密码</div>
      <el-form :model="changeForm" status-icon :rules="rules" ref="changeForm">
        <el-form-item
          label="手机号"
          label-width="120px"
          prop="phone"
          style="margin-bottom: 11px"
        >
          <el-col :span="18">
            <el-input
              type="text"
              @input="phoneInput"
              placeholder="请输入您的手机号"
              v-model="changeForm.phone"
            />
          </el-col>
        </el-form-item>
        <div style="height: 20px">
          <span
            v-show="!changeForm.password"
            style="font-size: 12px; color: #606266"
          >
            请输入8~16位密码，且至少含大小写、特殊字符、数字中的三种
          </span>
        </div>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-col :span="18">
            <el-input
              type="password"
              show-password
              @input="passwordInput"
              placeholder="请设置您的密码"
              v-model="changeForm.password"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="确认密码" label-width="120px" prop="checkPassword">
          <el-col :span="18">
            <el-input
              type="password"
              show-password
              @input="checkPasswordInput"
              placeholder="请确认您的密码"
              v-model="changeForm.checkPassword"
            />
          </el-col>
        </el-form-item>
       <!-- <el-form-item label="验证码" label-width="120px" prop="passCode">
          <div>
            <el-col :span="18">
              <el-input
                type="passCode"
                @input="passCodeInput"
                placeholder="请输入验证码"
                style="width: 153px"
                v-model="changeForm.passCode"
              />
              <el-button
                icon="el-icon-mobile-phone"
                @click="getCode"
                style="width: 98.5px; padding: 0px; height: 40px"
                type="success"
                :disabled="(disabled = !show)"
              >
                <span v-show="show">获取验证码</span>
                <span v-show="!show" class="count">{{ count }} s</span>
              </el-button>
            </el-col>
          </div>
        </el-form-item> -->
        <el-form-item>
          <div class="button">
            <el-button
              type="primary"
              style="width: 120px; margin-left: 20px"
              @click="change('changeForm')"
              >确认</el-button
            >
            <el-button style="width: 120px; margin-left: 20px" @click="toLogin"
              >返回登录</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import api from "../api";
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      const reg =
        /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/;
      if (reg.test(value)) {
        return callback();
      }
      callback("请输入合法的手机号");
    };
    var validatePassWord = (rule, value, callback) => {
      var reg =
        /^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{8,16}$/;
      if (value === "") {
        callback(new Error("请输入密码!"));
      } else if (value.length < 8 || value.length > 16) {
        callback(new Error("请输入8~16位密码!"));
      } else if (!reg.test(value)) {
        callback(new Error("密码至少需含大小写、特殊字符、数字中的三种!"));
      } else {
        callback();
      }
    };
    var validateCheckPassWord = (rule, value, callback) => {
      var reg =
        /^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{8,16}$/;
      if (value === "") {
        callback(new Error("请确认密码!"));
      } else if (value != this.changeForm.password) {
        callback(new Error("两次输入的密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePassCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码!"));
      } else {
        callback();
      }
    };
    return {
      show: true, // 初始启用按钮
      count: 60, // 初始化次数
      timer: null,
      temp: "",
      authCode: "",
      changeForm: {
        phone: "",
        password: "",
        checkPassword: "",
        passCode: "",
      },
      rules: {
        password: [
          {
            validator: validatePassWord,
            trigger: "blur",
          },
        ],
        phone: [
          {
            validator: validatePhone,
            trigger: "blur",
          },
        ],
        checkPassword: [
          {
            validator: validateCheckPassWord,
            trigger: "blur",
          },
        ],
        passCode: [
          {
            validator: validatePassCode,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    phoneInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 英文+数字+特殊字符；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.changeForm.phone = str;
    },
    passwordInput(val) {
      let codeReg = new RegExp("[A-Za-z0-9~!@#$%&*()_+-=<>,.?;:]+"), //正则 英文+数字+特殊字符；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.changeForm.password = str;
    },
    checkPasswordInput(val) {
      let codeReg = new RegExp("[A-Za-z0-9~!@#$%&*()_+-=<>,.?;:]+"), //正则 英文+数字+特殊字符；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.changeForm.checkPassword = str;
    },
    passCodeInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 英文+数字+特殊字符；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.changeForm.passCode = str;
    },
    change(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
			var resPWD = new URLSearchParams();
			resPWD.append("phoneNumber", this.changeForm.phone);
			resPWD.append("newPswd", this.changeForm.password);
			api.resetPswd(resPWD).then((res) => {
			  if (res.data == "1") {
			    this.$message({
			      message: "修改成功!即将返回登录!",
			      type: "success",
			    });
			    this.$router.push({ path: "/login" });
			  }
			});
		}
      });
	},
    change2(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.temp !== "" && this.temp !== this.changeForm.phone) {
            //发送的验证码与手机号不匹配
            this.$message.error(
              "输入的验证码与输入的手机号不匹配，请检查您的手机号!"
            );
          } else {
            //判断当前用户输入的验证码是否与发送的验证码一致
            if (this.authCode != this.changeForm.passCode) {
              //用户输入的验证码不匹配
              this.$message.error("验证码错误!");
            } else {
              //验证码正确，发送修改密码请求
              var resPWD = new URLSearchParams();
              resPWD.append("phoneNumber", this.changeForm.phone);
              resPWD.append("newPswd", this.changeForm.password);
              api.resetPswd(resPWD).then((res) => {
                if (res.data == "1") {
                  this.$message({
                    message: "修改成功!即将返回登录!",
                    type: "success",
                  });
                  this.$router.push({ path: "/login" });
                }
              });
            }
          }
        } else {
          return;
        }
      });
    },
    getCode() {
      this.$refs["changeForm"].validateField("phone", (err) => {
        if (err) {
          console.log("未通过");
          return;
        } else {
          //验证手机号是否注册过
          let param = new URLSearchParams();
          param.append("phoneNumber", this.changeForm.phone);
          api.isPhoneRegistered(param).then((res) => {
            if (res.data != "1") {
              //该手机号未注册
              this.$message.error("该手机号未注册!请更换手机号!");
            } else {
              //发送验证码
              api.getAuthCode(param).then((res0) => {
                this.tackBtn(); //验证码倒数60秒
                this.temp = this.changeForm.phone;
                if (res0.data == "-1") {
                  return;
                } else {
                  this.authCode = res0.data;
                  // console.log(this.sureCode);
                }
              });
            }
          });
        }
      });
    },
    tackBtn() {
      if (!this.timer) {
        this.count = 60;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= 60) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer); // 清除定时器
            this.timer = null;
          }
        }, 1000);
      }
    },
    toLogin() {
      this.$router.push("/login");
    },
  },
};
</script>

<style lang="less" scoped>
.register {
  position: fixed;
  height: 100%;
  width: 100%;
  position: fixed;
  background: url("../static/image/back.jpg");
  background-size: cover;
  .box-card {
    margin-top: 5%;
    margin-left: 54.2%;
    border: 2px solid #bdbfc1;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 15px;
    width: 500px;
    height: 450px;
  }
}
</style>